<?php

namespace app\admin\model\scanwork;

use think\Model;

/**
 * 系统配置模型
 */
class SystemConfig extends Model
{
    // 表名
    protected $name = 'scanwork_system_config';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    
    // 配置类型
    public function getConfigTypeList()
    {
        return [
            'string' => __('字符串'),
            'number' => __('数字'),
            'json' => __('JSON'),
            'boolean' => __('布尔值')
        ];
    }

    // 配置分组
    public function getConfigGroupList()
    {
        return [
            'system' => __('系统配置'),
            'code' => __('编码配置'),
            'work' => __('工作配置'),
            'quality' => __('质量配置'),
            'wage' => __('工资配置'),
            'trace' => __('溯源配置')
        ];
    }

    // 获取配置值
    public function getConfigValueAttr($value, $data)
    {
        $configType = $data['config_type'] ?? 'string';
        
        switch ($configType) {
            case 'number':
                return is_numeric($value) ? floatval($value) : 0;
            case 'boolean':
                return $value == '1' || $value === true || $value === 'true';
            case 'json':
                return json_decode($value, true) ?: [];
            default:
                return $value;
        }
    }

    // 设置配置值
    public function setConfigValueAttr($value, $data)
    {
        $configType = $data['config_type'] ?? 'string';
        
        switch ($configType) {
            case 'boolean':
                return $value ? '1' : '0';
            case 'json':
                return is_array($value) ? json_encode($value, JSON_UNESCAPED_UNICODE) : $value;
            default:
                return $value;
        }
    }

    // 获取配置
    public static function getConfig($key, $default = null)
    {
        $config = self::where('config_key', $key)->find();
        if ($config) {
            return $config->config_value;
        }
        return $default;
    }

    // 设置配置
    public static function setConfig($key, $value, $type = 'string', $group = 'system', $description = '')
    {
        $config = self::where('config_key', $key)->find();
        
        if ($config) {
            $config->save([
                'config_value' => $value,
                'config_type' => $type,
                'config_group' => $group,
                'description' => $description
            ]);
        } else {
            self::create([
                'config_key' => $key,
                'config_value' => $value,
                'config_type' => $type,
                'config_group' => $group,
                'description' => $description
            ]);
        }
    }

    // 获取分组配置
    public static function getGroupConfigs($group)
    {
        $configs = self::where('config_group', $group)->select();
        $result = [];
        
        foreach ($configs as $config) {
            $result[$config->config_key] = $config->config_value;
        }
        
        return $result;
    }

    // 批量设置配置
    public static function setConfigs($configs)
    {
        foreach ($configs as $key => $value) {
            if (is_array($value)) {
                self::setConfig($key, $value['value'], $value['type'] ?? 'string', $value['group'] ?? 'system', $value['description'] ?? '');
            } else {
                self::setConfig($key, $value);
            }
        }
    }

    // 初始化默认配置
    public static function initDefaultConfigs()
    {
        $defaultConfigs = [
            'workorder_system_version' => [
                'value' => '1.0.0',
                'type' => 'string',
                'group' => 'system',
                'description' => '小工单系统版本'
            ],
            'auto_generate_codes' => [
                'value' => '1',
                'type' => 'boolean',
                'group' => 'system',
                'description' => '是否自动生成编码'
            ],
            'code_prefix_customer' => [
                'value' => 'KH',
                'type' => 'string',
                'group' => 'code',
                'description' => '客户编码前缀'
            ],
            'code_prefix_employee' => [
                'value' => 'RY',
                'type' => 'string',
                'group' => 'code',
                'description' => '员工编码前缀'
            ],
            'code_prefix_process' => [
                'value' => 'GX',
                'type' => 'string',
                'group' => 'code',
                'description' => '工序编码前缀'
            ],
            'code_prefix_product' => [
                'value' => 'PD',
                'type' => 'string',
                'group' => 'code',
                'description' => '产品编码前缀'
            ],
            'code_prefix_plan' => [
                'value' => 'JH',
                'type' => 'string',
                'group' => 'code',
                'description' => '计划编码前缀'
            ],
            'code_prefix_allocation' => [
                'value' => 'FP',
                'type' => 'string',
                'group' => 'code',
                'description' => '分配编码前缀'
            ],
            'code_prefix_report' => [
                'value' => 'BG',
                'type' => 'string',
                'group' => 'code',
                'description' => '报工编码前缀'
            ],
            'code_prefix_wage' => [
                'value' => 'GZ',
                'type' => 'string',
                'group' => 'code',
                'description' => '工资编码前缀'
            ],
            'code_prefix_trace' => [
                'value' => 'SY',
                'type' => 'string',
                'group' => 'code',
                'description' => '溯源编码前缀'
            ],
            'default_work_hours_per_day' => [
                'value' => '8',
                'type' => 'number',
                'group' => 'work',
                'description' => '默认每日工作小时数'
            ],
            'overtime_threshold_hours' => [
                'value' => '8',
                'type' => 'number',
                'group' => 'work',
                'description' => '加班阈值小时数'
            ],
            'quality_check_required' => [
                'value' => '1',
                'type' => 'boolean',
                'group' => 'quality',
                'description' => '是否必须质检'
            ],
            'auto_calculate_wage' => [
                'value' => '1',
                'type' => 'boolean',
                'group' => 'wage',
                'description' => '是否自动计算工资'
            ],
            'traceability_enabled' => [
                'value' => '1',
                'type' => 'boolean',
                'group' => 'trace',
                'description' => '是否启用溯源功能'
            ]
        ];

        self::setConfigs($defaultConfigs);
    }

    // 获取系统信息
    public static function getSystemInfo()
    {
        return [
            'version' => self::getConfig('workorder_system_version', '1.0.0'),
            'auto_generate_codes' => self::getConfig('auto_generate_codes', true),
            'quality_check_required' => self::getConfig('quality_check_required', true),
            'auto_calculate_wage' => self::getConfig('auto_calculate_wage', true),
            'traceability_enabled' => self::getConfig('traceability_enabled', true),
            'default_work_hours' => self::getConfig('default_work_hours_per_day', 8),
            'overtime_threshold' => self::getConfig('overtime_threshold_hours', 8)
        ];
    }

    // 获取编码配置
    public static function getCodeConfigs()
    {
        return self::getGroupConfigs('code');
    }

    // 生成编码
    public static function generateCode($type, $id = null)
    {
        $prefix = self::getConfig("code_prefix_{$type}", strtoupper($type));
        $year = date('Y');
        
        if ($id) {
            return $prefix . '-' . $year . '-' . str_pad($id, 3, '0', STR_PAD_LEFT);
        }
        
        // 获取最后编码
        $lastCode = self::where('config_key', "code_prefix_{$type}")->find();
        if ($lastCode) {
            $lastNumber = 1;
        } else {
            $lastNumber = 0;
        }
        
        return $prefix . '-' . $year . '-' . str_pad($lastNumber + 1, 3, '0', STR_PAD_LEFT);
    }
}
